import { electronApp, is, optimizer } from '@electron-toolkit/utils'
import { BrowserWindow, app, type BrowserWindowConstructorOptions } from 'electron'
import type { createWindow, initWindow } from '../../types'
import { generateWindowUuid } from '../../utils'
import icon from '../../../../resources/images/logo-64x64.ico?asset'
import { join } from 'path'

const IS_DEV = process.env.NODE_ENV === 'development'

const winURL =
  process.env.NODE_ENV === 'development' ? `http://localhost:9080` : `out/renderer/index.html`

const basicWindowConfig: BrowserWindowConstructorOptions = {
  transparent: !IS_DEV,
  center: true,
  frame: false,
  autoHideMenuBar: true,
  titleBarStyle: 'hidden',
  alwaysOnTop: IS_DEV,
  resizable: false,
  icon,
  webPreferences: {
    preload: join(__dirname, '../preload/index.js'),
    sandbox: false,
    devTools: IS_DEV,
    nodeIntegration: true,
    contextIsolation: false,
    webSecurity: false
  }
}

export const collectionOfWindows: Record<string, BrowserWindow> = {}

const initWindow: initWindow = (
  routerPath: string,
  BrowserWindowConfig: BrowserWindowConstructorOptions
): BrowserWindow => {
  // 防止重复打开新窗口
  if (collectionOfWindows[routerPath] && !collectionOfWindows[routerPath].isDestroyed())
    return collectionOfWindows[routerPath]

  collectionOfWindows[routerPath] = new BrowserWindow({
    ...basicWindowConfig,
    ...BrowserWindowConfig
  })

  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    collectionOfWindows[routerPath].loadURL(`${process.env['ELECTRON_RENDERER_URL']}/${routerPath}`)
  } else {
    collectionOfWindows[routerPath].loadFile(winURL, { hash: routerPath })
  }

  collectionOfWindows[routerPath].on('closed', () => {
    collectionOfWindows[routerPath] = null as unknown as BrowserWindow
  })

  return collectionOfWindows[routerPath]
}

/**
 * 创建新窗口
 * @param routerPath 路由 hash 值 (只能传hash值)
 * @param BrowserWindowConfig 创建窗口的基本配置
 */
const createWindow: createWindow = (
  routerPath: string,
  BrowserWindowConfig: BrowserWindowConstructorOptions
): Promise<BrowserWindow> => {
  return new Promise<BrowserWindow>((resolve, reject) => {
    try {
      app.whenReady().then(() => {
        electronApp.setAppUserModelId(generateWindowUuid())

        app.on('browser-window-created', (_, window) => {
          optimizer.watchWindowShortcuts(window)
        })

        resolve(initWindow(routerPath, BrowserWindowConfig))

        app.on('activate', function () {
          if (BrowserWindow.getAllWindows().length === 0 || BrowserWindowConfig.parent)
            resolve(initWindow(routerPath, BrowserWindowConfig))
        })
      })

      app.on('window-all-closed', () => {
        if (process.platform !== 'darwin') {
          app.quit()
        }
      })
    } catch (error) {
      reject(error)
    }
  })
}

export default createWindow
